package com.erp.service.util.net;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import com.erp.service.util.JSONHelper;

import android.text.TextUtils;
import android.util.Log;

public class NDJSONRequest extends NDHttpRequest implements IEntityRequest {

	private static final String TAG = "NDHttpRequest";

	public NDJSONRequest(Map<String, String> defaultHeader) {
		super(defaultHeader);
	}

	public NDJSONRequest(Map<String, String> defaultHeader, HttpClient client) {
		super(defaultHeader, client);

	}

	public NDJSONRequest(Map<String, String> defaultHeader, HttpClient client,
			String encoding) {
		super(defaultHeader, client, encoding);
	}

	/**
	 * 将实体序列化为json的post参数
	 * 
	 * @param entity
	 * @return
	 */
	public StringEntity getStringEntity(Object entity) {
		StringEntity stringEntity = null;
		try {
			if (entity != null) {
				String entityJSON = JSONHelper.serialize(entity);
				Log.i(TAG, entityJSON);
				// stringEntity = new
				// StringEntity("[{\"EnMobileSyncClientSlaveList\":[{\"AutoCode\":2,\"dAddTime\":\"\\/Date(1322473684000+0800)\\/\",\"lSyncMainCode\":1,\"lSyncState\":0,\"lTableNameCode\":1,\"lType\":1,\"sTableCode\":\"2\"}]");
				stringEntity = new StringEntity(entityJSON, HTTP.UTF_8);
				stringEntity.setContentEncoding("UTF-8");
				stringEntity.setContentType("application/json");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stringEntity;
	}

	/**
	 * 向指定URL发送的请求，返回实体
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            传入的参数键值对，内部会将传入的值进行UrlEncode
	 * @param RequestMethod
	 *            GET或POST
	 * @throws Exception
	 * 
	 * @return URL所代表远程资源的响应
	 */
	public <T> T sendForEntity(String url, List<NameValuePair> params,
			Object entity, String requestMethod, Class<T> returnType)
			throws Exception {
		String jsonString = send(url, params, requestMethod,
				getStringEntity(entity)).toString();
		if (TextUtils.isEmpty(jsonString))
			return null;
		return JSONHelper.<T> deserialize(returnType, jsonString);
	}

	/**
	 * 向指定URL发送的请求，返回实体列表
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            传入的参数键值对，内部会将传入的值进行UrlEncode
	 * @param RequestMethod
	 *            GET或POST
	 * @throws Exception
	 * 
	 * @return URL所代表远程资源的响应
	 */
	public <T> List<T> sendForEntityList(String url,
			List<NameValuePair> params, Object entity, String requestMethod,
			Class<T> returnType) throws Exception {
		String jsonString = send(url, params, requestMethod,
				getStringEntity(entity)).toString();
		if (TextUtils.isEmpty(jsonString))
			return null;
		return JSONHelper.deserializeArray(returnType, jsonString);
	}

	/**
	 * 向指定URL发送的请求，返回JSON对象
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            传入的参数键值对，内部会将传入的值进行UrlEncode
	 * @param RequestMethod
	 *            GET或POST
	 * @throws Exception
	 * 
	 * @return URL所代表远程资源的响应
	 */
	public JSONObject sendForJSONObject(String url, List<NameValuePair> params,
			Object entity, String requestMethod) throws Exception {
		HttpEntity stringEntity = null;

		if (entity != null) {
			entity = new StringEntity(JSONHelper.serialize(entity));
		}
		return new JSONObject(send(url, params, requestMethod, stringEntity)
				.toString());
	}

	/**
	 * 向指定URL发送的请求，返回JSON数组
	 * 
	 * @author ccl
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            传入的参数键值对，内部会将传入的值进行UrlEncode
	 * @param RequestMethod
	 *            GET或POST
	 * @throws Exception
	 * 
	 * @return URL所代表远程资源的响应
	 */
	public JSONArray sendForJSONArray(String url, List<NameValuePair> params,
			Object entity, String requestMethod) throws Exception {
		HttpEntity stringEntity = null;
		if (entity != null)
			entity = new StringEntity(JSONHelper.serialize(entity));
		return new JSONArray(send(url, params, requestMethod, stringEntity)
				.toString());
	}

	/**
	 * @author ccl
	 * @param url
	 *            上传地址
	 * @param params
	 *            参数
	 * @param file
	 *            上传文件
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws AuthenticationException
	 */
	public long upload(String url, HttpParams params, File file,
			long startPosition, UploadProgressListener listener)
			throws ClientProtocolException, IOException,
			AuthenticationException {
		try {
			String uploadLengthString = upload(url, params.toNameValuePairs(),
					file, startPosition, listener).toString();
			return Long.parseLong(uploadLengthString);
		} catch (Exception e) {
			Log.e(TAG, e.getStackTrace().toString());
			e.printStackTrace();
		}
		return -1;
	}
}
